//
//  YCPhotoViewerModel.m
//  PhotoViewer
//
//  Created by 唐可雄 on 17/2/12.
//  Copyright © 2017年 swustyc. All rights reserved.
//

#import "YCPhotoViewerModel.h"

#import "YCPhotoViewController.h"
#import "YCPhotoViewerViewController.h"

@interface YCPhotoViewerModel()

@property (nonatomic, strong) UIStoryboard *storyboard;

@end

@implementation YCPhotoViewerModel

#pragma mark - NSObject

- (id)init {
    self = [super init];
    if (self != nil) {
        _curIndex = 0;
    }
    return self;
}

#pragma mark - Properties

- (UIStoryboard *)storyboard {
    if (_storyboard == nil) {
        _storyboard = [UIStoryboard storyboardWithName:@"PhotoViewer" bundle:[NSBundle bundleForClass:[self class]]];
    }
    
    return _storyboard;
}

#pragma mark - Methods

- (YCPhotoViewController *)viewControllerAtIndex:(NSUInteger)index {
    if (self.photoes.count == 0 || index >= self.photoes.count) {
        return nil;
    }
    
    YCPhotoViewController *vcPhoto = [self.storyboard instantiateViewControllerWithIdentifier:@"vcPhoto"];
    vcPhoto.photo = self.photoes[index];
    
    return vcPhoto;
}

- (NSUInteger)indexOfViewController:(YCPhotoViewController *)viewController {
    return [self.photoes indexOfObject:viewController.photo];
}

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    YCPhotoViewerViewController *vcPhotoViewer = (YCPhotoViewerViewController *)pageViewController.delegate;
    
    if (vcPhotoViewer.pageAnimationFinished == NO) {
        return nil;
    }
    
    NSUInteger index = [self indexOfViewController:(YCPhotoViewController *)viewController];
    if (index == 0 || index == NSNotFound) {
        return nil;
    }
    
    index--;
    
    _curIndex = index;
    return [self viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    YCPhotoViewerViewController *vcPhotoViewer = (YCPhotoViewerViewController *)pageViewController.delegate;
    
    if (vcPhotoViewer.pageAnimationFinished == NO) {
        return nil;
    }
    
    NSUInteger index = [self indexOfViewController:(YCPhotoViewController *)viewController];
    if (index == self.photoes.count-1 || index == NSNotFound) {
        return nil;
    }
    
    index++;
    
    _curIndex = index;
    return [self viewControllerAtIndex:index];
}

@end
